package com.example.flex.controller.generator;

import cn.hutool.core.io.resource.ClassPathResource;
import com.example.flex.domain.generator.TableEntity;
import com.example.flex.service.generator.CodeService;
import com.example.flex.utils.redis.RedisCache;
import com.example.flex.utils.response.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: 不是菜鸡爱编程
 * @Date: 2023/10/25/21:43
 * @Description:
 */
@RestController
@RequestMapping("code")
public class CodeController {
    /**
     * 生成文件路径后缀
     */
    private static final String FILES_PATH_SUFFIX="/src/main/resources/";
    /**
     * 生成文件在resources下指定文件夹下
     */
    private static final String FILES_PATH="generated-code/";
    /**
     * 替换target后的正则表达式
     */
    private static final String REPLACE_TARGET_REGEX="/target.*";
    @Autowired
    private CodeService codeService;
    @Autowired
    private RedisCache redisCache;

    @GetMapping("/generator")
    public BaseResponse<?> generateCode(@RequestParam String uuid){
        List<TableEntity> tableList = redisCache.getCacheArray(uuid, TableEntity.class);
        ClassPathResource resource = new ClassPathResource(FILES_PATH);
        String generatorCodePath = resource.getAbsolutePath().replaceFirst(REPLACE_TARGET_REGEX, "")+FILES_PATH_SUFFIX+FILES_PATH;
        boolean generatedFlag = codeService.generateCode(tableList, generatorCodePath);
        if(generatedFlag){
            return BaseResponse.success().setMessage("代码生成成功");
        }else{
            return BaseResponse.error().setMessage("代码生成失败");
        }
    }
}
